<script setup>
import { ref, defineOptions } from 'vue'
import { getHotwords, getKeywords, SearchWords } from "@/api/getAxios_2.ts"
import TopTitle from "@/components/TopTitle.vue"
import { showToast } from 'vant';


const hotwords = ref([])
getHotwords().then((res) => {
    // console.log(res);
    hotwords.value = res.data.data
})

// 搜索记录
const records = ref([])

const isShow = ref(false)
const keywords = ref([])
const words = ref('')
// 防抖
const debounce = () => {
    let timer;
    return function (value) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            getKeywords(value).then((res) => {
                // 是否显示搜索词列表
                isShow.value = true
                keywords.value = res.data.data
            })
        }, 400);
    }
}
let dbFun = debounce()

//***************************************** */
// 一开始读取本地并渲染
records.value = JSON.parse(localStorage.getItem('record'))
// 当选择了关键词时，进行本地存储并渲染
const getRecord = (title) => {
    let record = JSON.parse(localStorage.getItem('record')) || []
    for (var i = 0; i < record.length; i++) {
        if (record[i] == title) {
            record.splice(i, 1)
            for (var j = i; j < record.length - 1; j++) {
                record[j] = record[j + 1]
            }
        }
    }
    record.unshift(title)
    localStorage.setItem('record', JSON.stringify(record))
    records.value = JSON.parse(localStorage.getItem('record'))
}


//***************************************** */


// 提前声明搜索结果数组
const chooseList = ref([])

// 设置清除按钮
const isAllDel = ref(false)
const inputHandler = (e) => {
    // 是否显示清除搜索内容的按钮
    if (e.target.value) {
        isAllDel.value = true
    } else {
        isAllDel.value = false
    }
    chooseList.value = []
    // console.log(e.key);
    if (e.key == 'Enter') {
        words.value = document.querySelector('.search').value
        SearchWords(words.value, '1').then((res) => {
            chooseList.value = res.data.data.list
            getRecord(words.value)
        })
    }
    dbFun(e.target.value);
}

//***************************************** */

// 选择关键词
const pageNo = ref('1')
const chooseWord = (e) => {
    isShow.value = false
    document.querySelector('.search').value = e.target.innerText
    words.value = e.target.innerText
    SearchWords(words.value, '1').then((res) => {
        chooseList.value = res.data.data.list
        getRecord(words.value)
    })

}

//***************************************** */

// 万和亿的换算
const getNumType = (num) => {
    if (num / 10000 >= 10000) {
        return (num / 100000000).toFixed(1) + '亿人气值'
    } else {
        return (num / 10000).toFixed(1) + '万人气值'
    }
}

//***************************************** */
// 返回顶部
// const isShowBackTOP = ref(false)
const detailList = ref(null)
const backTop = () => {
    detailList.value.scrollTo({ top: 0, behavior: 'smooth' });
}
//***************************************** */


// 清除搜索值
const delAllValue = () => {
    document.querySelector('.search').value = ''
    keywords.value = []
    chooseList.value = []
    document.querySelector('.search').focus()
    isAllDel.value = false
}
//***************************************** */


let flag = true
// 触底请求更多数据
const scrollHandler = (e) => {
    // console.log(types.value[types.value.length - 1]);
    const li = document.querySelector('.totally').children[chooseList.value.length - 1]
    // console.log(li.offsetTop);
    // console.log(e.target.scrollTop + 680);
    if (e.target.scrollTop + 980 >= li.offsetTop && flag) {
        flag = false
        pageNo.value = (Number(pageNo.value) + 1).toString()
        SearchWords(
            words.value, pageNo.value
        ).then((res) => {
            // console.log(res);
            res.data.data.list.forEach(o => chooseList.value.push(o))
            flag = true
            if (res.data.data.list.length == 0) {
                showToast('已经到底啦！')
                return
            }
        })
    }
}

//***************************************** */

const chooseOne = (title) => {
    document.querySelector('.search').value = title
    SearchWords(title, '1').then((res) => {
        chooseList.value = res.data.data.list
        // console.log(title);
        getRecord(title)
    })
}


//***************************************** */

// 搜索事件
const searchHandler = () => {
    let title = document.querySelector('.search').value
    if (title) {
        SearchWords(title, '1').then((res) => {
            // console.log(res);
            chooseList.value = res.data.data.list
            getRecord(title)
        })
    }
}
//***************************************** */
// 删除搜索记录
const deleteHandler = () => {
    let record = []
    localStorage.setItem('record', JSON.stringify(record))
    records.value = JSON.parse(localStorage.getItem('record'))
}


</script>
<template>
    <div class="box">
        <TopTitle :flag="true">
            <span class="iconfont icon-sousuo sousuo"></span>
            <input type="text" class="search" placeholder="搜索书名、书号、作者" @keyup="inputHandler($event)">
            <span class="iconfont icon-shanchuanniu alldel" v-show="isAllDel" @click="delAllValue"></span>
            <span class="gosearch" @click="searchHandler">搜索</span>
        </TopTitle>
        <ul class="list" v-if="keywords.length !== 0 && keywords[0] !== '查询无结果' && isShow">
            <li v-for="data in keywords" @click="chooseWord($event)">{{ data }}</li>
        </ul>
        <div class="detailList" v-if="chooseList.length !== 0" ref="detailList" @scroll="scrollHandler($event)">
            <p class="result">搜索结果</p>
            <div class="backTop">
                <span class="iconfont icon-fanhuidingbu1 back" @click="backTop"></span>
            </div>
            <ul class="totally" ref="box">
                <li v-for="res in chooseList" @click="$router.push(`/BookInfo?storyId=${res.id}`)">
                    <div class="storyImg">
                        <img :src="res.smallCover" alt="">
                    </div>
                    <div class="infoMsg">
                        <div class="name_person">
                            <h2>{{ res.name
                            }}</h2>
                            <div class="fire_person">
                                <span class="iconfont icon-fire"></span>
                                {{ getNumType(res.fireValue) }}
                            </div>
                        </div>
                        <div class="author_1">{{ res.authorName }} 著</div>
                        <div class="detail_1">{{ res.introduce }}</div>
                    </div>
                </li>
            </ul>
        </div>
        <div class="allSearch">
            <p>大家都在搜</p>
            <ul>
                <li v-for="item in hotwords" @click="chooseOne(item.keyWord)">{{ item.keyWord
                }}</li>
            </ul>
        </div>
        <div class="allSearch">
            <p>搜索记录
                <span class="delete" @click="deleteHandler">删除</span>
            </p>
            <ul>
                <li v-for="cos in records" @click="chooseOne(cos)">{{ cos }}</li>
            </ul>
        </div>
    </div>
</template>

<style scoped lang='less'>
@import "//at.alicdn.com/t/c/font_4308477_5g7nf339e6o.css";

.search {
    height: 30px;
    border-radius: 20px;
    padding: 0 22px;
    border: 1px solid #c0c0c0;
    margin-right: 20px;
    width: 210px;
}

span.gosearch {
    color: #d9646f;
    font-size: 18px;
}

.allSearch {
    background-color: #fff;
    margin-bottom: 10px;
    position: relative;

    p {
        display: flex;
        align-items: center;
        font-weight: bold;
        line-height: 20px;
        padding: 10px;

        &::before {
            content: '';
            display: inline-block;
            width: 5px;
            height: 20px;
            background-color: #d9646f;
            margin-right: 10px;
        }

        .delete {
            position: absolute;
            right: 10px;
            color: #da6973;
            font-weight: normal;
        }
    }

    ul {

        display: flex;
        flex-wrap: wrap;

        li {
            padding: 5px 10px;
            border-radius: 20px;
            border: 1px solid #eee;
            margin: 10px;
        }
    }
}

.list {
    background-color: #fff;
    position: absolute;
    z-index: 1;
    width: 100%;

    li {
        padding: 10px 20px;
        border-bottom: 1px solid #eee;
    }
}

.box {}

.sousuo {
    position: absolute;
    left: 5px;
}

.alldel {
    position: absolute;
    right: 65px;
}

.detailList {
    background-color: #fff;
    z-index: 1;
    position: absolute;
    width: 100%;
    height: 92vh;
    overflow: scroll;

    &::-webkit-scrollbar {
        display: none;
    }


    // 返回顶部
    .backTop {
        height: 50px;
        position: fixed;
        bottom: 50px;
        right: 0;
        width: 50px;

        // font-size: 30px;
        .back {
            font-size: 30px;
            color: aquamarine;
        }
    }

    p.result {
        padding: 10px 10px;
        display: flex;
        align-items: center;

        &::before {
            content: "";
            display: inline-block;
            width: 5px;
            height: 20px;
            margin-right: 10px;
            background-color: #d9646f;
        }
    }

    .totally {
        padding: 10px;

        &::-webkit-scrollbar {
            display: none;
        }

        li {
            margin: 0 0;
            height: 34vw;
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid #eee;

            .storyImg {
                width: 25vw;
                height: 100%;
                border-radius: 10px;
                margin-right: 10px;
                box-shadow: 0px 15px 7px -11px rgba(0, 0, 0, .3);

                img {
                    border-radius: 10px;
                    width: 100%;
                    height: 100%;
                }
            }

            .infoMsg {
                display: flex;
                flex-direction: column;
                width: 68vw;

                .name_person {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 10px;

                    h2 {
                        width: 35vw;
                        font-size: 20px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }

                    .fire_person {
                        font-size: 14px;
                        color: #d7bf7c;

                        span {
                            // margin-right: 10px;
                            color: #cabc79;
                        }
                    }
                }

                .author_1 {
                    font-size: 14px;
                    margin-bottom: 10px;
                    color: #645c57;
                }

                .detail_1 {
                    overflow: hidden;
                    white-space: wrap;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    color: #3c3b41;
                }
            }
        }
    }
}
</style>